<template>
    <div id="settlementDetails">
        <el-dialog
       
        :visible.sync="dialogVisible"
        top="10vh"
        :close-on-click-modal="false"
        :before-close="handleClose"
        >
            <span slot="title" style="    display: flex;align-items: center;">
                <span>
                    {{obj.storeName+'门店结算单'}}
                </span>
                <span style="font-size: 14px">日期：
                    <span>{{obj.gmtStart + '-' + obj.gmtEnd}}</span>
                </span>
            </span>
            <!-- 分成明细 -->
            <div>
                <el-table :data="profitData" border stripe :summary-method="getSummaries" show-summary>
                    <el-table-column label="科目" prop="subjectName"></el-table-column>
                    <el-table-column label="商品类型" prop="goodsType">
                        <template slot-scope="scope">
                            <el-tag size="small" :type="scope.row.goodsType == 0 ? 'info' : scope.row.goodsType == 1 ? 'success' : '' ">
                                {{scope.row.goodsType == 0 ? '普通商品' : scope.row.goodsType == 1 ? '特卖商品' : '--' }}
                            </el-tag>
                        </template>
                    </el-table-column>
                    <el-table-column label="销售额" prop="totalOrderAmount"></el-table-column>
                    <el-table-column label="分润比例" prop="profitRate"></el-table-column>
                    <el-table-column label="分成金额" prop="profitAmount"></el-table-column>
                    <el-table-column label="操作" width="80">
                        <template slot-scope="scope">
                            <el-button size="mini" type="text" @click="handleDownLoad(scope.row)">明细下载</el-button>
                        </template>
                    </el-table-column>
                </el-table>
            </div>
            <!-- 费用明细 -->
            <div style="margin: 10px 0">
                <el-table :data="expenseData" border stripe>
                    <!-- <el-table-column label="序号">
                        <template slot-scope="scope">
                        {{scope.$index+1}} 
                        </template>
                    </el-table-column> -->
                    <el-table-column label="科目" prop="subjectName" width="100">
                        <template slot-scope="scope">
                            <section v-if="scope.$index != 0 && scope.$index != 1">
                                <el-select size="mini" v-model="scope.row.subjectName" @chang="handleChange">
                                    <el-option value="费用" label="费用"></el-option>
                                    <el-option value="补贴" label="补贴"></el-option>
                                </el-select>
                            </section>
                            <span v-else>{{scope.row.subjectName}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="类型" prop="subjectType" width="100">
                        <template slot-scope="scope">
                            <section v-if="scope.$index != 0 && scope.$index != 1"  @chang="handleChange">
                                <el-select size="mini" v-model="scope.row.subjectType">
                                    <el-option value="手提袋" label="手提袋"></el-option>
                                    <el-option value="流水台" label="流水台"></el-option>
                                    <el-option value="模特" label="模特"></el-option>
                                    <el-option value="耗材" label="耗材"></el-option>
                                    <el-option value="其他" label="其他"></el-option>
                                </el-select>
                            </section>
                            <span v-else>{{scope.row.subjectType}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="金额" prop="expenseAmount" width="100">
                        <template slot-scope="scope">
                            <section v-if="scope.$index != 0 && scope.$index != 1">
                                <el-input size="mini" v-model="scope.row.expenseAmount" @chang="handleChange">
                                    <template v-if="scope.row.subjectName == '费用'" slot="prepend">-</template>
                                </el-input>
                            </section>
                            <span v-else>{{scope.row.expenseAmount}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="备注" prop="remark">
                        <template slot-scope="scope">
                            <section v-if="scope.$index != 0 && scope.$index != 1">
                                <el-input type="textarea" autosize size="mini" v-model="scope.row.remark" @chang="handleChange"></el-input>
                            </section>
                            <span v-else>{{scope.row.remark}}</span>
                        </template>
                    </el-table-column>
                    <el-table-column label="操作" width="60" >
                        <template slot-scope="scope">
                            <el-button type="text" v-if="scope.$index != 0 && scope.$index != 1" size="mini" @click.native.prevent="deleteRow(scope.$index, expenseData)">删除</el-button>
                            <el-button type="text" v-if="scope.row.subjectType == '物流费'" size="mini" @click="handleRefersh">刷新</el-button>
                        </template>
                    </el-table-column>
                </el-table>

                <div class="cus-btn" v-if="obj.settleStatus == -1 || obj.settleStatus == 0">
                    <el-button style="width: 100%;" icon="el-icon-plus" @click="handleClickTableItem">添加其他费用</el-button>
                </div>
            </div>
            <!-- 汇总 -->
            <div>
                <el-table :data="totalData" border stripe>
                    <el-table-column label="分成金额" prop="profitAmount"></el-table-column>
                    <el-table-column label="费用金额" prop="expenseAmount"></el-table-column>
                    <el-table-column label="补贴金额" prop="allowanceAmount"></el-table-column>
                    <el-table-column label="结转金额" prop="carriedAmount"></el-table-column>
                    <el-table-column label="结算金额" prop="settleAmount"></el-table-column>
                </el-table>
            </div>
            <span slot="footer" class="dialog-footer" v-if="buttontype == 'edit'">
                <el-button  size="small" type="primary" v-if="!inputchang && !buttonchange" @click="handleSubmit">提 交</el-button>
                <el-button size="small" @click="handleSave">保 存</el-button>
            </span>
        </el-dialog>
    </div>
</template>
<script>
    export default {
        props: ['isShow', 'obj', 'buttontype'],
        data() {
            return {
                profitData: [], //分成
                expenseData: [], // 费用
                item: {
                    subjectName: '',
                    subjectType: '',
                    apportionRate: '',
                    expenseAmount: '',
                    remark: '',
                    isAdd: true

                },
                totalData: [],
                inputchang: true,
                buttonchange: true,
                type: '',
                downUrl: process.env.BASE_API + '/ddaigo-platform/excel/exportStoreSettlesProfit' 
            }
        },
        computed: {
            dialogVisible: {
                get() {
                    return this.isShow;
                },
                set() {}
            }
        },
        mounted() {
            if(this.obj.settleStatus== -1) {

                this.getStoreIntoList()
                this.getExpenseList()
            }else{
                this.checkSettlementDetails()
            }
            
        },
        methods: {
            handleClose() {
                this.$confirm('确认关闭？').then(_ => {
                    this.$emit('cancelShow', false)
                    this.$emit('getStoreSettlementList')
                }).catch(_ => {});
            },
            /**1.0获取门店科目分成列表 */
            getStoreIntoList() {
                let params= {
                    data: {
                        storeNo: this.obj.storeNo,
                        startTime: this.obj.gmtStart,
                        endTime: this.obj.gmtEnd
                    }
                }
                this.$server.financialControlApi.getStoreInto(params).then(res => {
                    this.profitData= res.data
                })
            },
            /**查询费用明细 */
            getExpenseList() {
                var arr
                let params= {
                    settleId: this.obj.settleId,
                    settleOrderId: this.obj.id,
                    storeNo: this.obj.storeNo
                }
                this.$server.financialControlApi.getExpenseList(params).then(res => {
                    if(this.type== 'refersh') {
                        arr=this.expenseData.splice(0,1)
                        this.expenseData.splice(0,0,arr[0])

                    }else{
                        this.expenseData= res.data
                    }
                })
            },
            // 保存后查看
            checkSettlementDetails() {
                this.totalData= []
                this.$server.financialControlApi.checkSettlementDetails(this.obj.settleId).then(res => {
                    this.profitData= res.data.profitList
                    this.expenseData= res.data.expenseList
                    
                    this.totalData.push(
                        {
                            allowanceAmount: res.data.allowanceAmount,
                            carriedAmount: res.data.carriedAmount,
                            expenseAmount: res.data.expenseAmount,
                            profitAmount: res.data.profitAmount,
                            settleAmount: res.data.settleAmount,
                        }
                    )
                })
            },
            /**删除行 */
            deleteRow(index, rows) {
                this.buttonchange=true
                rows.splice(index, 1);
            },
            /**刷新 */
            handleRefersh() {
                this.buttonchange= true
                this.type= 'refersh'
                this.getExpenseList()
            },
            handleChange() {
                this.inputchang= true
            },
          
            /**添加行 */
            handleClickTableItem() {
                this.expenseData.push(
                    {
                        settleOrderId: this.obj.id,
                        settleId: this.obj.settleId,
                        subjectName: '',
                        subjectType: '',
                        apportionRate: null,
                        expenseAmount: '',
                        remark: null,
                        isAdd: true
                    }
                )
                this.buttonchange= true
            },
              /**下载明细 */
            handleDownLoad(scope) {
                let params= {
                    data: {
                        storeNo: this.obj.storeNo,
                        saleType: scope.subjectName == '销售' ? 'order' : scope.subjectName == '退货' ? 'return' : 'total',
                        goodsType: scope.goodsType,
                        gmtStart: this.obj.gmtStart,
                        gmtEnd: this.obj.gmtEnd
                    }
                }
                let obj= {
                    params: params,
                    type: 'v1',
                    url: this.downUrl,
                    name: (scope.goodsType == 0 ? '普通商品' : '特卖商品') + scope.subjectName
                }
                this.$server.excelApi.downLoadExcelPost(obj)
            },
            /**保存 */
            handleSave() {
                var newprofitList= this.profitData
                newprofitList.forEach(item => {
                    item.profitRate= (''+item.profitRate).indexOf('%') > -1 ? item.profitRate.replace(/%/g,'')/100 : item.profitRate
                })
                var newExpenseData= [];
                console.log(this.expenseData, 'expenseData')
                this.expenseData.forEach((item,index) => {
                    if(item.subjectName != ''  && item.subjectType !='' && item.subjectName != null && item.subjectType !=null ){
                        if(item.isAdd) {
                            delete item.isAdd
                        }
                        if(item.subjectName == '费用') {
                            item.expenseAmount= item.expenseAmount > 0 ? '-' + item.expenseAmount : item.expenseAmount 
                        }
                        item.expenseAmount= +item.expenseAmount
                        newExpenseData.push(item)
                    }
                })
                console.log(newExpenseData, 'newExpenseData')
                let params= {
                    storeNo: this.obj.storeNo,
                    storeName: this.obj.storeName,
                    settleOrderId: this.obj.id,
                    gmtStart: this.obj.gmtStart,
                    gmtEnd: this.obj.gmtEnd,
                    profitList: newprofitList,
                    expenseList: newExpenseData,
                    settleId: this.obj.settleId,
                    settleStatus: 0
                }
                this.$server.financialControlApi.saveSettlement(params).then(res => {
                    this.$message({
                        message: res.message,
                        type: 'success',
                        duration: 1500
                    })

                    /**查询费用 */
                    this.checkSettlementDetails()
                    newExpenseData= []
                    newprofitList= []
                    /**查询统计 */
                    this.inputchang= false
                    this.buttonchange= false
                })
            },
            /**提交 */
            handleSubmit() {
                let params= {
                    settleId: this.obj.settleId,
                    settleStatus: 1,   
                }
                this.$server.financialControlApi.changeSettlementStatus(params).then(res => {
                    this.$emit('cancelShow', false)
                    this.$emit('getStoreSettlementList')
                })
            },
            getSummaries(param) {
                const { columns, data } = param;
                const sums = [];
                columns.forEach((column, index) => {
                    if (index === 0) {
                        sums[index] = '合计';
                        return;
                    }
                    if(column.property == 'goodsType' ||column.property == 'profitRate') {
                        sums[index]= ''
                        return;
                    }
                    const values =  data.map(item => Number(item[column.property]));
                    if (!values.every(value => isNaN(value))) {
                        sums[index] = values.reduce((prev, curr) => {
                            const value = Number(curr);
                            if (!isNaN(value)) {
                                return prev + curr;
                            } else {
                                return prev;
                            }
                        }, 0);
                        if(sums[index] != 0) {
                            sums[index]= sums[index].toFixed(2)
                        }
                        sums[index] += ' 元';
                    } else {
                        sums[index] = '';
                    }
                });
                return sums;
            },
        }
    }
</script>
<style lang="less" scoped>
    .cus-btn {
        margin: 20px 0;
        .el-button {
            width: 100%;
            border: 1px dashed #999;
            color: #999;
            font-weight: 400
        }
    }
</style>